package abio.XasML.rpc
{
	import abio.XasML.util.tween;
	import org.spicefactory.lib.reflect.ClassInfo;
	
	import flash.display.Loader;
	import flash.events.Event;
	import flash.net.URLRequest;
	import flash.utils.Dictionary;
	import flash.utils.Proxy;
	import flash.utils.flash_proxy;
	
	import mx.core.mx_internal;
	import mx.messaging.messages.AbstractMessage;
	import mx.rpc.AsyncToken;
	import mx.rpc.events.ResultEvent;
	
	public class classLoader extends Proxy
	{
		static private const loaderDict:Dictionary=new Dictionary();
		private var url:String=null;

		public function classLoader(url:String)
		{
			this.url=url;
			if(classLoader.loaderDict.hasOwnProperty(url)==false){
				classLoader.loaderDict[url]=new Loader();
				(classLoader.loaderDict[url] as Loader).load(new URLRequest(url));
			}
		}
		
		override flash_proxy function getProperty(name:*):*
		{
			return function delayedCall(...args):AsyncToken{
				var result:AsyncToken=new AsyncToken(new AbstractMessage());
				if((classLoader.loaderDict[url] as Loader).content==null){
					(classLoader.loaderDict[url] as Loader).contentLoaderInfo.addEventListener(Event.COMPLETE, function COMPLETE(e:Event):void{
						var tempObject:Object=ClassInfo.forClass((classLoader.loaderDict[url] as Loader).contentLoaderInfo.applicationDomain.getDefinition(name) as Class).newInstance(args);
						result.mx_internal::applyResult(new ResultEvent(typeof(tempObject),false,true,tempObject));
					});				
				}else{
					tween.delayedCall(1, function DELAYEDCALL():void{
						var tempObject:Object=ClassInfo.forClass((classLoader.loaderDict[url] as Loader).contentLoaderInfo.applicationDomain.getDefinition(name) as Class).newInstance(args);
						result.mx_internal::applyResult(new ResultEvent(typeof(tempObject),false,true,tempObject));
					});
				}
				return result;
			}
		}
	}
}